import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
// 关键修复：同时导入 deleteSelectedItems 和 addgwc
import { deleteSelectedItems, addgwc } from '../store/login/index';
import './Gou.css';

// 计算rem值的工具函数（1rem = 16px）
const rem = (px) => `${px / 16}rem`;

const Gou = () => {
  // 使用useSelector直接从Redux获取购物车数据
  const { list } = useSelector(state => state.login);

  // 本地状态：只管理选中状态和编辑状态
  const [selectedIds, setSelectedIds] = useState([]);
  const [isEditing, setIsEditing] = useState(false);

  // 计算合计金额
  const totalPrice = list.reduce((sum, item) => {
    return selectedIds.includes(item.id) ? sum + (item.price * item.num) : sum;
  }, 0);

  // 全选状态
  const allSelected = list.length > 0 && list.every(item => selectedIds.includes(item.id));

  const dispatch = useDispatch();

  // 单个商品选中状态切换
  const handleItemSelect = (id) => {
    setSelectedIds(prev =>
      prev.includes(id)
        ? prev.filter(selectedId => selectedId !== id)
        : [...prev, id]
    );
  };

  // 全选/反选功能
  const handleAllSelect = () => {
    setSelectedIds(allSelected ? [] : list.map(item => item.id));
  };

  // 处理删除选中商品
  const handleDeleteSelected = () => {
    if (selectedIds.length === 0) {
      alert('请先选择要删除的商品');
      return;
    }

    if (window.confirm(`确定要删除选中的 ${selectedIds.length} 个商品吗？`)) {
      dispatch(deleteSelectedItems(selectedIds)); // 传递选中的ID数组
      setSelectedIds([]); // 清空选中状态
      setIsEditing(false); // 退出编辑状态
    }
  };

  // 新增：单独处理数量增减的方法（避免原addgwc逻辑冲突）
  const handleChangeNum = (item, type) => {
    console.log(item)
    if (type === 'minus' && item.num <= 1) return; // 数量最小为1
    // 传递包含id和操作类型的参数给addgwc
    dispatch(addgwc({
      id: item.id,
      type: type // 'add' 增加 / 'minus' 减少
    }));
  };
  return (
    <div style={{
      width: '100%',
      height: '100vh',
      backgroundColor: '#f5f5f5',
      fontFamily: 'Arial, sans-serif',
      paddingBottom: '10rem' // 预留底部栏空间
    }}>
      {/* 顶部导航栏 */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        backgroundColor: '#e52222',
        color: 'white',
        padding: `${rem(10)} ${rem(15)}`,
        height: "10rem"
      }}>
        <div style={{ marginRight: rem(15), cursor: 'pointer' }}>
          <svg xmlns="http://www.w3.org/2000/svg" width="8rem" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth={rem(2)} strokeLinecap="round" strokeLinejoin="round">
            <polyline points="15 18 9 12 15 6" />
          </svg>
        </div>
        <div style={{
          flex: 1,
          fontSize: "5rem",
          fontWeight: 'bold',
          textAlign: 'center'
        }}>购物车</div>
        <div style={{ fontSize: "3rem", cursor: 'pointer' }} onClick={() => setIsEditing(!isEditing)}>
          {isEditing ? '完成' : '编辑'}
        </div>
      </div>

      {/* 商品列表区域 */}
      <div style={{
        flex: 1,
        overflowY: 'auto',
        padding: `${rem(10)} 0`
      }}>
        {list.length > 0 ? (
          list.map(ele => (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                backgroundColor: 'white',
                padding: rem(15),
                marginBottom: rem(10),
                borderBottom: `1px solid #e0e0e0`,
                height: "30rem"
              }}
              key={ele.id}
            >
              {/* 复选框 */}
              <div style={{ marginRight: rem(15) }}>
                <input
                  type="checkbox"
                  id={`item-${ele.id}`}
                  style={{ width: "10rem" }}
                  checked={selectedIds.includes(ele.id)}
                  onChange={() => handleItemSelect(ele.id)}
                />
              </div>

              {/* 商品信息 */}
              <div style={{ display: 'flex', alignItems: 'center', flex: 1 }}>
                <img
                  src={ele.image}
                  alt={ele.name}
                  style={{
                    width: "15rem",
                    marginRight: rem(15),
                    objectFit: 'cover'
                  }}
                />
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  <div style={{
                    fontSize: "4rem",
                    marginBottom: rem(5),
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical'
                  }}>
                    {ele.description}
                  </div>
                  <div style={{
                    fontSize: "4rem",
                    marginBottom: rem(5),
                    color: '#333'
                  }}>
                    {ele.name}
                  </div>
                  <div style={{
                    fontSize: "4rem",
                    color: '#999',
                    marginBottom: rem(5)
                  }}>
                    尺寸：{ele.Tabs}
                  </div>
                  <div style={{
                    fontSize: "4rem",
                    color: '#e52222',
                    fontWeight: 'bold'
                  }}>
                    ¥{ele.orderAmount}
                  </div>
                </div>
              </div>

              {/* 数量控制（修复：使用新的handleChangeNum方法） */}
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <button
                  style={{
                    width: "6rem",
                    backgroundColor: '#f5f5f5',
                    border: `1px solid #e0e0e0`,
                    cursor: 'pointer'
                  }}
                  onClick={() => handleChangeNum(ele, 'minus')}
                >
                  -
                </button>
                <span style={{
                  width: "6rem",
                  textAlign: 'center',
                  margin: `0 ${rem(5)}`,
                  fontSize: "5rem"
                }}>
                  {ele.num || 1}
                </span>
                <button
                  style={{
                    width: "6rem",
                    backgroundColor: '#f5f5f5',
                    border: `1px solid #e0e0e0`,
                    cursor: 'pointer'
                  }}
                  onClick={() => handleChangeNum(ele, 'add')}
                >
                  +
                </button>
              </div>
            </div>
          ))
        ) : (
          <div style={{
            textAlign: 'center',
            padding: rem(30),
            color: '#999',
            fontSize: rem(16)
          }}>
            购物车是空的，快去添加商品吧～
          </div>
        )}
      </div>

      {/* 底部结算栏 */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        backgroundColor: 'white',
        padding: `${rem(10)} ${rem(15)}`,
        borderTop: `1px solid #e0e0e0`,
        height: "10rem",
        boxSizing: 'border-box',
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        zIndex: 100
      }}>
        {/* 全选按钮 */}
        <div style={{ marginRight: rem(15), display: 'flex', alignItems: 'center' }}>
          <input
            type="checkbox"
            id="select-all"
            style={{ width: "10rem", margin: 0 }}
            checked={allSelected}
            onChange={handleAllSelect}
          />
          <label
            htmlFor="select-all"
            style={{ marginLeft: rem(5), fontSize: "4rem", color: '#333' }}
          >
            全选
          </label>
        </div>

        {/* 根据编辑状态显示不同内容 */}
        {isEditing ? (
          <div style={{ flex: 1, display: 'flex', justifyContent: 'flex-end' }}>
            <button
              style={{
                backgroundColor: '#e52222',
                color: 'white',
                border: 'none',
                padding: `${rem(10)} ${rem(20)}`,
                borderRadius: rem(4),
                cursor: 'pointer',
                fontSize: "4rem",
                whiteSpace: 'nowrap'
              }}
              onClick={handleDeleteSelected}
            >
              删除 ({selectedIds.length})
            </button>
          </div>
        ) : (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ fontSize: "4rem", color: '#e52222', marginLeft: "4rem", fontWeight: 'bold' }}>
              合计：¥{totalPrice.toFixed(2)}
            </div>
            <button style={{
              backgroundColor: '#e52222',
              color: 'white',
              border: 'none',
              padding: `${rem(10)} ${rem(20)}`,
              borderRadius: rem(4),
              cursor: 'pointer',
              fontSize: "4rem",
              whiteSpace: 'nowrap'
            }}>
              去结算
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

export default Gou;